package durst.action.account;

import java.sql.SQLException;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import durst.action.CalendarBasicAction;
import durst.data.Account;
import durst.data.Event;
import durst.data.Invite;
import durst.data.UserCalendar;
import durst.data.dao.DaoFactory;
import durst.data.dao.impl.AccountDao;

public class InviteFriendActionBean extends CalendarBasicAction {
	@Validate(mask="\\w+")
	private String query;
	
	@ValidateNestedProperties(@Validate(field = "id", required = true))
	private Event event;
	
	@DefaultHandler
	@SuppressWarnings("unchecked")
	public Resolution query() throws SQLException {
		DaoFactory.getInstance().createDao(Event.class).refresh(event);
		DaoFactory.getInstance().createDao(UserCalendar.class).refresh(event.getParent());
		
		Account friend = ((AccountDao<Account, Integer>) DaoFactory.getInstance().createDao(
				Account.class)).queryByUsername(query);

		if (event.getParent().getOwner().equals(context.getAccount()) && friend != null) {
			for (Invite inv : event.getInvites())
				if (inv.getInvitee().equals(friend) && inv.getEvent().equals(event))
					return new ForwardResolution("/blank.jsp");
			DaoFactory.getInstance().createDao(Invite.class).create(new Invite(friend, event, false));
		}
	
		return new ForwardResolution("/blank.jsp");
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public String getQuery() {
		return query;
	}
	
	public void setEvent(Event event) {
		this.event = event;
	}
	
	public Event getEvent() {
		return this.event;
	}
}
